﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Mvc.XForms.Utilities {
	public static class HttpRequestBaseHelper {
		/// <summary>
		/// Returns a URL with listed variables removed in string.Format format. eg:
		/// /Customers/Search.aspx?var1={0}&amp;var2={1}
		/// </summary>
		public static string UrlFormat(this HttpRequestBase req, string[] varsToReplace, bool removeEmptyVars) {
			var qsStr = req.QueryString.RemoveKeys(varsToReplace, removeEmptyVars).ToHttpValueString();
			var qs = new StringBuilder(qsStr);

			for (int i = 0; i < varsToReplace.Length; i++) {
				if (qs.Length != 0)
					qs.Append("&amp;");
				qs.AppendFormat("{0}={{{1}}}", varsToReplace[i], i);
			}

			return string.Format("{0}?{1}", req.Path, qs);
		}

		/// <summary>
		/// Reads a value from form or querystring, returning string.Empty for a null value
		/// </summary>
		public static string ReadFromRequest(this HttpRequestBase req, string key) {
			string outValue = string.Empty;
			if (req.Form[key] != null)
				outValue = req.Form[key];
			else if (req.QueryString[key] != null)
				outValue = req.QueryString[key];
			return outValue;
		}
	}
}
